package cn.ccbom.bom.interview.util.script.task;

import cn.ccbom.bom.interview.util.script.script.EngineClient;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.net.URL;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Data
@EqualsAndHashCode(callSuper = true)
public class TaskItem extends AbstractRunStatus<String> {
    private String title;
    private String url;
    private String script;

    public TaskItem(String title) {
        this.setId(IdUtil.fastSimpleUUID());
        this.title = title;
        this.setCreateTime(LocalDateTime.now());
        this.setStatus(RunStatus.CREATE);
    }

    public Object run(EngineClient engineClient) {
        try {
            this.setStartTime(LocalDateTime.now());
            this.setOver(false);
            this.setStatus(RunStatus.RUNNING);
            if (StrUtil.isNotBlank(url)) {
                URL u = URLUtil.url(url);
                script = IoUtil.readUtf8(u.openStream());
            }
            Object result = engineClient.execute(title, script);
            this.setStatus(RunStatus.SUCCESS);
            return result;
        } catch (Exception ex) {
            this.setStatus(RunStatus.ERROR);
        } finally {
            this.setEndTime(LocalDateTime.now());
            this.setOver(true);
            this.setCost(LocalDateTimeUtil.between(getStartTime(), getEndTime(), ChronoUnit.MILLIS));
        }
        return null;
    }
}